package com.epoch.platform.common.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/common/popup")
public class CommonPopupController extends BaseController{
	
	public void init() {
		String sqlKey = this.getPara("sqlKey");
        String metaStr = Db.getSql(sqlKey);
        Kv meta = JSON.parseObject(metaStr, Kv.class);
        String rowId = meta.getAs("rowId");
        List<Map<String, String>> colDatas = meta.getAs("colDatas");
        String queryUrl = meta.getAs("queryUrl");
        this.setAttr("_rowId", rowId);
        this.setAttr("_colDatas", colDatas);
        if (StringUtils.isNotEmpty(queryUrl)) {
            this.setAttr("_queryUrl", queryUrl);
        }
        String keepParamsKeyStr = this.getPara("keepParamsKeyStr");
        this.keepPara(StringUtils.split(keepParamsKeyStr, ','));
        this.render("/common/commonPopup.html");
	}
	
	public void list() {
        String sqlKey = this.getPara("_cmnPop_sqlKey");
        Boolean paginate = this.getParaToBoolean("_cmnPop_paginate");
        String metaStr = Db.getSql(sqlKey);
        Kv meta = JSON.parseObject(metaStr, Kv.class);
        String sqlKeyCore = sqlKey.substring(0, sqlKey.lastIndexOf("."));
        Kv popupParams = this.commonPopupParams();
        SqlPara sqlPara = Db.getSqlPara(sqlKeyCore, popupParams);
        Page<Record> resultList = null;
        if (Boolean.TRUE.equals(paginate)) {
            int pageNumber = popupParams.getInt("pageNumber");
            int pageSize = popupParams.getInt("pageSize");
            String countSqlSuffix = meta.getAs("countSqlSuffix");
            if (StringUtils.isNotEmpty(countSqlSuffix)) {
                SqlPara countSqlPara = Db.getSqlPara(sqlKeyCore + "." + countSqlSuffix, popupParams);
                resultList = Db.paginateByFullSql(pageNumber, pageSize, countSqlPara.getSql(), sqlPara.getSql(), sqlPara.getPara());
            } else {
                resultList = Db.paginate(pageNumber, pageSize, sqlPara);
            }
        } else {
            List<Record> list = Db.find(sqlPara);
            int rows = list == null ? 0 : list.size();
            resultList = new Page<Record>(list, 1, rows, 1, rows);
        }
        this.renderJson(resultList);
    }
}
